package com.zliblike_platform.service.impl;

import com.zliblike_platform.entity.CommentLike;
import com.zliblike_platform.mapper.CommentLikeMapper;
import com.zliblike_platform.mapper.CommentMapper;
import com.zliblike_platform.service.CommentLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 评论点赞服务实现
 */
@Service
public class CommentLikeServiceImpl implements CommentLikeService {

    @Autowired
    private CommentLikeMapper commentLikeMapper;
    
    @Autowired
    private CommentMapper commentMapper;

    @Override
    @Transactional
    public boolean toggleLike(Integer userId, Integer commentId) {
        boolean hasLiked = hasUserLiked(userId, commentId);
        
        if (hasLiked) {
            // 取消点赞
            commentLikeMapper.delete(Long.valueOf(commentId), Long.valueOf(userId));
            commentMapper.decrementLikes(Long.valueOf(commentId));
            return false;
        } else {
            // 添加点赞
            CommentLike commentLike = new CommentLike();
            commentLike.setCommentId(Long.valueOf(commentId));
            commentLike.setUserId(Long.valueOf(userId));
            commentLikeMapper.insert(commentLike);
            commentMapper.incrementLikes(Long.valueOf(commentId));
            return true;
        }
    }

    @Override
    public int getLikeCount(Integer commentId) {
        List<Long> commentIds = new ArrayList<>();
        commentIds.add(Long.valueOf(commentId));
        // 由于没有直接提供countLikes方法，需要通过其他方式获取点赞数
        return commentLikeMapper.selectLikedCommentIds(commentIds, null).size();
    }

    @Override
    public boolean hasUserLiked(Integer userId, Integer commentId) {
        CommentLike like = commentLikeMapper.selectByCommentIdAndUserId(
                Long.valueOf(commentId), 
                Long.valueOf(userId));
        return like != null;
    }

    @Override
    public List<Integer> getUserLikedComments(Integer userId) {
        // 由于没有直接提供获取用户点赞的评论列表方法，需要通过其他方式
        // 这里简化处理，实际场景可能需要结合comment表查询所有评论ID再筛选
        List<Long> commentIds = new ArrayList<>(); // 临时解决方案
        List<Long> likedCommentIds = commentLikeMapper.selectLikedCommentIds(commentIds, Long.valueOf(userId));
        return likedCommentIds.stream()
                .map(Long::intValue)
                .collect(Collectors.toList());
    }
} 